package com.kstech.test.padxmledit;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * Created by lenovo on 2016/9/7.
 */
public class ListEditFragment extends Fragment {
    private ListView lv;
    private Button btn;
    private Button btnSave;
    private EditAdapter editAdapter;
    private String fileName = "/storage/sdcard1/new_modules.xml";
    private ListFragMent f;
    private ProgressDialog dialog = null;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    editAdapter.notifyDataSetChanged();
                    break;
                case 1:
                    editAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.listeditfragment, null);
        lv = (ListView) view.findViewById(R.id.pad_lv_edit);
        btn = (Button) view.findViewById(R.id.btn_to_edit);
        btnSave = (Button) view.findViewById(R.id.btn_to_save);
        editAdapter = new EditAdapter();
        f = (ListFragMent) getFragmentManager().findFragmentByTag("list");
        lv.setAdapter(editAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.i("hahah", "点击-------");
                Log.i("hahah", "点击-------" + Globals.list_edit.size());
                Globals.list_edit.remove(Globals.list_edit.get(i));
                handler.sendEmptyMessage(1);
            }
        });
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Globals.list_edit.size() > 0) {
                    Globals.qcItem = Globals.list_edit.getFirst();
                    startActivity(new Intent(getActivity(), EditDataActivity.class));
                }else{
                    Toast.makeText(getActivity(),"没有要修改的参数！！",Toast.LENGTH_SHORT).show();
                }

            }
        });
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyAsyncTask task = new MyAsyncTask();
                task.execute();
            }
        });
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i(">>>>>>", "list edit fragment update");
        editAdapter.notifyDataSetChanged();
    }

    class EditAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return Globals.list_edit.size();
        }

        @Override
        public Object getItem(int i) {
            return Globals.list_edit.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = View.inflate(getActivity(), R.layout.list_item_dataset, null);
            }
            TextView tv = (TextView) view.findViewById(R.id.pad_tv_data);
            if (Globals.list_edit.size() == 0) {
                tv.setText("没有数据，请稍后。。。。");
            } else {
                tv.setText(Globals.list_edit.get(i).toString());
            }
            return view;
        }
    }
    class MyAsyncTask extends AsyncTask<Void,Integer,Void>{
        @Override
        protected Void doInBackground(Void... voids) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = null;
            try {
                builder = factory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Document doc = builder.newDocument();
            Element root = doc.createElement("Device");
            root.setAttribute("Id",Globals.device.getID());
            root.setAttribute("Name",Globals.device.getName());
            root.setAttribute("DevBornDate",Globals.device.getDevBornDate());
            root.setAttribute("DevDieDate",Globals.device.getDevDieDate());
            root.setAttribute("DevStatus",Globals.device.getDevStatus());
            doc.appendChild(root);
            //Resource 添加到xml
//            Element Resource = doc.createElement("Resource");
//            root.appendChild(Resource);
            /**
             * Resource中MsgSet 和ImageSet 写入xml文件------------------------------开始
             */
//            Element MsgS = doc.createElement("MsgSet");
//            for(int i=0;i<Globals.device.getMsgSet().size();i++){
//                Element Mg = doc.createElement("Msg");
//                Mg.setAttribute("Id",Globals.device.getMsgSet().get(i).getId());
//                Mg.setAttribute("RefName",Globals.device.getMsgSet().get(i).getRefName());
//                Mg.setAttribute("Content",Globals.device.getMsgSet().get(i).getContent());
//                MsgS.appendChild(Mg);
//            }
//            Element ImageSet = doc.createElement("ImageSet");
//            for(int i=0;i<Globals.device.getImageSet().size();i++){
//                Element IG = doc.createElement("Image");
//                IG.setAttribute("Id",Globals.device.getImageSet().get(i).getId());
//                IG.setAttribute("RefName",Globals.device.getImageSet().get(i).getRefName());
//                IG.setAttribute("Content",Globals.device.getImageSet().get(i).getContent());
//                ImageSet.appendChild(IG);
//            }
//            Resource.appendChild(MsgS);
//            Resource.appendChild(ImageSet);
            /**
             * Resource中MsgSet 和ImageSet 写入xml文件------------------------------------结束
             */
            //DataSet添加到xml
            Element EDataSet = doc.createElement("DataSet");
            root.appendChild(EDataSet);
            for(int i=0;i<Globals.device.getDSItems().size();i++){
                Element DSItem = doc.createElement("DSItem");
                DSItem.setAttribute("Name", Globals.device.getDSItems().get(i).getName());
                DSItem.setAttribute("DataType", Globals.device.getDSItems().get(i).getDataType());
                DSItem.setAttribute("Unit", Globals.device.getDSItems().get(i).getUnit());
                DSItem.setAttribute("DecLen", Globals.device.getDSItems().get(i).getDeclen()+"");
                DSItem.setAttribute("LinkTo", Globals.device.getDSItems().get(i).getLinkTo()+"");
                DSItem.setAttribute("Rows",Globals.device.getDSItems().get(i).getRows()+"");
                DSItem.setAttribute("Value",Globals.device.getDSItems().get(i).getFloatValues()+"");
                EDataSet.appendChild(DSItem);
            }
            Element EJ1939 = doc.createElement("J1939");
            EJ1939.setAttribute("NodeAddr",Globals.device.getmJ1939().getNodeAddr());
            EJ1939.setAttribute("Cycle",Globals.device.getmJ1939().getCycle());
            EJ1939.setAttribute("TaskPrio",Globals.device.getmJ1939().getTaskPrio());
            root.appendChild(EJ1939);
            for(int i=0;i<Globals.device.getmJ1939().getPGList().size();i++){
                Element EPG= doc.createElement("PG");
                EPG.setAttribute("Type",Globals.device.getmJ1939().getPGList().get(i).getType());
                EPG.setAttribute("Dir",Globals.device.getmJ1939().getPGList().get(i).getDir());
                EPG.setAttribute("Prio",Globals.device.getmJ1939().getPGList().get(i).getPrio());
                EPG.setAttribute("Len",Globals.device.getmJ1939().getPGList().get(i).getLen());
                EPG.setAttribute("Rate",Globals.device.getmJ1939().getPGList().get(i).getRate());
                EPG.setAttribute("PGN",Globals.device.getmJ1939().getPGList().get(i).getPGN());
                EPG.setAttribute("SA",Globals.device.getmJ1939().getPGList().get(i).getSA());
                EPG.setAttribute("Req",Globals.device.getmJ1939().getPGList().get(i).getReq());
                EPG.setAttribute("ReqCyc",Globals.device.getmJ1939().getPGList().get(i).getReqCyc());

                for(int j=0;j<Globals.device.getmJ1939().getPGList().get(i).getSPList().size();j++){
                    Element ESP = doc.createElement("SP");
                    ESP.setAttribute("Type",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getType());
                    if(Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getSPN()!=null){
                        ESP.setAttribute("SPN",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getSPN());
                    }
                    ESP.setAttribute("SByte",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getSByte());
                    ESP.setAttribute("SBit",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getSBit());
                    ESP.setAttribute("Bytes",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getSByte());
                    ESP.setAttribute("Bits",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getBits());
                    ESP.setAttribute("Res",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getRes());
                    ESP.setAttribute("Off",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getOff());
                    ESP.setAttribute("Ref",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getRef());
                    if(Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getDTCList()!=null){
                        for(int d=0;d<Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getDTCList().size();d++){
                            Element EDTC = doc.createElement("DTC");
                            EDTC.setAttribute("FMI",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getDTCList().get(d).getFMI());
                            EDTC.setAttribute("MsgId",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getDTCList().get(d).getMsgId());
                            EDTC.setAttribute("Icon",Globals.device.getmJ1939().getPGList().get(i).getSPList().get(j).getDTCList().get(d).getIcon());
                            ESP.appendChild(EDTC);
                        }
                    }
                    EPG.appendChild(ESP);
                }
                EJ1939.appendChild(EPG);
            }
            Element EQCSet = doc.createElement("QCSet");
            root.appendChild(EQCSet);
            Log.i("XML",Globals.device.getQCset().size()+" ------------------------------------");
            for(int qc=0;qc<Globals.device.getQCset().size();qc++){
                Element EQCItem = doc.createElement("QCItem");
                EQCItem.setAttribute("Id",Globals.device.getQCset().get(qc).getID());
                EQCItem.setAttribute("Name",Globals.device.getQCset().get(qc).getName());
                EQCItem.setAttribute("Require",Globals.device.getQCset().get(qc).getRequire());
                EQCItem.setAttribute("QCTimes",Globals.device.getQCset().get(qc).getQCTimes());
                EQCItem.setAttribute("ReadyTimeout",Globals.device.getQCset().get(qc).getReadyTimeout());
                EQCItem.setAttribute("QCTimeout",Globals.device.getQCset().get(qc).getQCTimeout());
                EQCSet.appendChild(EQCItem);
                Element EMsgs = doc.createElement("Msgs");
                EMsgs.setAttribute("ReadyMsg",Globals.device.getQCset().get(qc).getmMsgs().getReadyMsg());
                EMsgs.setAttribute("NotReadyMsg",Globals.device.getQCset().get(qc).getmMsgs().getNotReadyMsg());
                EMsgs.setAttribute("AbortMsg",Globals.device.getQCset().get(qc).getmMsgs().getAbortMsg());
                EMsgs.setAttribute("OkMsg",Globals.device.getQCset().get(qc).getmMsgs().getOkMsg());

                Element QCProgressMsg = doc.createElement("QCProgressMsg");
                for(int qp=0;qp<Globals.device.getQCset().get(qc).getmMsgs().getQCProgressMsg().size();qp++){
                    Element QCProgress = doc.createElement("QCProgress");
                    QCProgress.setAttribute("Code",Globals.device.getQCset().get(qc).getmMsgs().getQCProgressMsg().get(qp).Code);
                    QCProgress.setAttribute("Msg",Globals.device.getQCset().get(qc).getmMsgs().getQCProgressMsg().get(qp).Msg);
                    QCProgressMsg.appendChild(QCProgress);
                }
                Element QCErrMsg = doc.createElement("QCErrMsg");
                for(int qp=0;qp<Globals.device.getQCset().get(qc).getmMsgs().getQCErrMsg().size();qp++){
                    Element QCErr = doc.createElement("QCErr");
                    if(Globals.device.getQCset().get(qc).getmMsgs().getQCErrMsg().get(qp).Code!=null
                            &&Globals.device.getQCset().get(qc).getmMsgs().getQCErrMsg().get(qp).Msg!=null){
                        QCErr.setAttribute("Code",Globals.device.getQCset().get(qc).getmMsgs().getQCErrMsg().get(qp).Code);
                        QCErr.setAttribute("Msg",Globals.device.getQCset().get(qc).getmMsgs().getQCErrMsg().get(qp).Msg);
                    }else {
                        QCErr.setAttribute("Code"," ");
                        QCErr.setAttribute("Code"," ");
                    }
                    QCErrMsg.appendChild(QCErr);
                }
                EMsgs.appendChild(QCProgressMsg);
                EMsgs.appendChild(QCErrMsg);
                EQCItem.appendChild(EMsgs);

                Element QCParams = doc.createElement("QCParams");
                for(int i=0;i<Globals.device.getQCset().get(qc).getQCParams().size();i++){
                    Element QCParam = doc.createElement("QCParam");
                    QCParam.setAttribute("Param",Globals.device.getQCset().get(qc).getQCParams().get(i).Param);
                    QCParam.setAttribute("ValidMin",Globals.device.getQCset().get(qc).getQCParams().get(i).ValidMin);
                    QCParam.setAttribute("ValidMax",Globals.device.getQCset().get(qc).getQCParams().get(i).ValidMax);
                    QCParam.setAttribute("ValidAvg",Globals.device.getQCset().get(qc).getQCParams().get(i).ValidAvg);
                    QCParams.appendChild(QCParam);
                }
                EQCItem.appendChild(QCParams);

                Element ENVParams = doc.createElement("ENVParams");
                for(int i=0;i<Globals.device.getQCset().get(qc).getENVParams().size();i++){
                    Element ENVParam = doc.createElement("ENVParam");
                    ENVParam.setAttribute("Param",Globals.device.getQCset().get(qc).getENVParams().get(i).Param);
                    ENVParam.setAttribute("ValidMin",Globals.device.getQCset().get(qc).getENVParams().get(i).ValidMin);
                    ENVParam.setAttribute("ValidMax",Globals.device.getQCset().get(qc).getENVParams().get(i).ValidMax);
                    ENVParams.appendChild(ENVParam);
                }
                EQCItem.appendChild(ENVParams);
            }

            Element RealTimeSet = doc.createElement("RealTimeSet");
            root.appendChild(RealTimeSet);
            for(int i=0;i< Globals.device.getRealTimeSet().size();i++){
                Element RealTimeParam = doc.createElement("RealTimeParam");
                RealTimeParam.setAttribute("Name",Globals.device.getRealTimeSet().get(i).name);
                RealTimeSet.appendChild(RealTimeParam);
            }


            Transformer t = null;
            try {
                t = TransformerFactory.newInstance().newTransformer();
                t.setOutputProperty(OutputKeys.INDENT, "yes");
                t.setOutputProperty(OutputKeys.METHOD, "xml");
                File file = new File(fileName);
                if(!file.exists()){
                    file.createNewFile();
                }
                t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(file)));
            } catch (TransformerConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (TransformerFactoryConfigurationError e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (TransformerException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("hahah",">>>>>>>>>>>>>>开始保存到本地");
            dialog = ProgressDialog.show(getActivity(),"正在保存", "正在保存，请稍等...", false);//创建ProgressDialog
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Log.i("hahah",">>>>>>>>>>>>>>成功保存到本地");
            SystemClock.sleep(500);
            dialog.dismiss();
            Toast.makeText(getActivity(),"保存成功！！路径为"+fileName,Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
    }
}
